﻿using System.Collections.Generic;
using System.Linq;

namespace QPEngine
{
	[ObjectEvent]
	public class PlayerComponentEvent : ObjectEvent<PlayerComponent>, IAwake
	{
		public void Awake()
		{
			this.Get().Awake();
		}
	}
	
	public class PlayerComponent : Component
	{
		public static PlayerComponent Instance { get; private set; }

		public Player MyPlayer;
		
		private readonly Dictionary<long, Player> idPlayers = new Dictionary<long, Player>();

		public void Awake()
		{
			Instance = this;
		}
		
		public void Add(Player player)
		{
            this.idPlayers.Add(player.Info.Account,player);
        }

        public void Update(Player player)
        {
            if(!this.idPlayers.ContainsKey(player.Info.Account))
            {
                this.Add(player); return;
            }
            this.idPlayers.Remove(player.Info.Account);
            this.Add(player);
        }

		public Player Get(long id)
		{
			this.idPlayers.TryGetValue(id, out Player gamer);
            if (gamer == null) { this.idPlayers.TryGetValue(id - AppCost.DefineNumber, out gamer); }
            if (gamer == null) { this.idPlayers.TryGetValue(id + AppCost.DefineNumber, out gamer); }
            return gamer;
		}
        public Player Get(Session session)
        {
            Player p = default(Player);
            foreach (var item in this.idPlayers.Values)
            {
                if (item.session?.Id==session.Id) { p = item; }
                Log.Error("session.item.account="+item.Info.Account);
            }
            Log.Error("没有找到 seesion 对应的 Player");
            return p;
        }

		public void Remove(long id)
		{

            Log.Error("session.Remove=" + id);
            this.idPlayers.Remove(id);
		}

		public int Count
		{
			get
			{
				return this.idPlayers.Count;
			}
		}

		public Player[] GetAll()
		{
			return this.idPlayers.Values.ToArray();
		}

		public override void Dispose()
		{
			if (this.Id == 0)
			{
				return;
			}
			
			base.Dispose();

			foreach (Player player in this.idPlayers.Values)
			{
				player.Dispose();
			}

			Instance = null;
		}
	}
}